const msgUtil = {};

msgUtil.success = function (msg) {
    layui.use('layer', function () {
        let layer = layui.layer;
        layer.msg(msg, {icon: 1});
    });
}

msgUtil.error = function (msg) {
    layui.use('layer', function () {
        let layer = layui.layer;
        layer.msg(msg, {icon: 2});
    });
}

let iconDetail = function (id, title) {
    return `<i class="iconfont icon-icon-test" style="font-size: 20px; cursor: pointer;" title="${title}" data-toggle="modal" data-target="#allMsg1" id="${id}"></i>`
}

let iconUpdate = function (id, title) {
    return `<i class="iconfont icon-xiugai" style="font-size: 18px; cursor: pointer;" title="${title}" data-toggle="modal" data-target="#change" id="${id}"></i>`
}

let iconDelete = function (id, title) {
    return `<i class="iconfont icon-icon-test" style="font-size: 20px; cursor: pointer;" title="${title}" data-toggle="modal" data-target="#allMsg1" id="${id}"></i>`
}

let formatState = function (state) {

    switch (state) {
        case 0:
            return `<a href="" class="weikaishi">未开始</a>`;
        case 1:
            return `<a href="" class="jinxing">进行中</a>`;
        case 2:
            return `<a href="" class="jieshu">已结束</a>`;
    }
}

let autoSetVal = function (pre, data, split) {
    $(`[id^=${pre}]`).each(function () {
        let id = $(this).attr("id");
        $(this).val(data[id.substring(id.indexOf(split) + 1)])
    })
}

let autoGetValToObj = function (pre, split) {
    let obj = {};
    $(`[id^=${pre}]`).each(function () {
        let id = $(this).attr("id");
        // $(this).val(data[id.substring(id.indexOf(split) + 1)])
        obj[id.substring(id.indexOf(split) + 1)] = $(`#${id}`).val();
    })
    return obj;
}

const initSelectUtil = {};
initSelectUtil.initSelectToObj = function ($id, data, attr, child, childUUid) {

    let resultMap = {};
    let initSelectObj = {};
    let childArray = [];
    let childArrayObj = {};

    $id.empty();
    $id.append(`<option value="">全部</option>`);
    for (var i in data) {
        initSelectObj[data[i].uuid] = data[i][child];
        $id.append(`<option value="${data[i].uuid}">${data[i][attr]}</option>`);
        if (child != null && child != undefined) {
            for (let k in data[i][child]) {
                childArray.push(data[i][child][k])
                childArrayObj[data[i][child][k][childUUid]] = data[i][child][k];
            }
        }
    }
    resultMap.oneObj = initSelectObj;
    resultMap.twoObj = childArray;
    resultMap.thirdObj = childArrayObj;
    return resultMap;
}

initSelectUtil.initSelect = function ($id, data, attr) {
    $id.empty();
    $id.append(`<option value="">全部</option>`);
    for (var i in data) {
        $id.append(`<option value="${data[i].uuid}">${data[i][attr]}</option>`);
    }
}

initSelectUtil.initSelectNoAll = function ($id, data, attr) {
    $id.empty();
    for (var i in data) {
        $id.append(`<option value="${data[i].uuid}">${data[i][attr]}</option>`);
    }
}

initSelectUtil.initSelectAndOnly = function ($id, data, attr) {
    let sets = new Set();
    for (let i in data) {
        sets.add(data[i][attr]);
    }
    $id.empty();
    $id.append(`<option value="">全部</option>`);
    for (var j of sets) {
        for (var i in data) {
            if (j == data[i][attr]) {
                $id.append(`<option value="${data[i].uuid}">${data[i][attr]}</option>`);
                break;
            }
        }
    }
}


const utils = {};
utils.bindChangeUtil = function (id, targetId) {
    $(`#${id}`).on('change', function () {
        let uuid = $(this).val();
        $(`#${targetId}`).val(uuid);
    })
}

utils.getUrlParam = function () {
    try {
        var url = window.location.href;
        var result = url.split("?")[1];
        var keyValue = result.split("&");
        var obj = {};
        for (var i = 0; i < keyValue.length; i++) {
            var item = keyValue[i].split("=");
            obj[item[0]] = item[1];
        }
        return obj;
    } catch (e) {
        console.warn("There has no param value!");
    }
};


/*!
 * 数据验证工具类
 * 2016-12-30
 * wangbt
 */

/**
 * 相关认证的正则表达式
 */
var verificatRet = {
    // 身份证
    identityCard: /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$|^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}([0-9]|X)$/,
    //identityCard : /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}\d|[X]{1}$/,
    // 手机号
    mobile: /^((1[3|4|5|7|8][0-9]{1})+\d{8})$/,
    // 电子邮箱
    email: /^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/,
    // 座机
    phone: /^0\d{2,3}-?\d{7,8}$/,
    // 数字
    number: /^[0-9]*$/,
    // 非零正整数
    NZ_number: /^\+?[1-9][0-9]*$/,
    // 非零负整数
    _NZ_number: /^\-[1-9][0-9]*$/,
    // 非负整数（正整数 + 0）
    _noIntNumber: /^\d+$/,
    // 非正整数（负整数 + 0）
    noIntNumber: /^((-\d+)|(0+))$/,
    // 整数
    intNumber: /^-?\d+$/,
    // 正浮点小数
    doubleNumber: /^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$/,
    // 非正浮点小数（负浮点小数 + 0）
    _noDoubleNum: /^((-\d+(\.\d+)?)|(0+(\.0+)?))$/,
    // 负浮点小数
    _doubleNumber: /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/,
    // 浮点数
    double: /^(-?\d+)(\.\d+)?$/
};

/**
 * 验证工具类
 */
var verificat = {
    /** 非空验证 */
    isNotNull: function (source) {
        if (source != null && source != undefined && source != 'undefined' && source != "")
            return true;
        return false;
    },
    /**去空格后非空验证*/
    isNotNullTrim: function (source) {
        if (source != null && source != undefined && source != 'undefined' && $.trim(source) != "")
            return true;
        return false;
    },
    /**
     * 验证字符串最大长度【注：一个汉字的长度为2】
     * @param source 字符串
     * @param num 指定的长度
     */
    textMaxVer: function (source, num) {
        if (source.replace(/[^\x00-\xff]/g, "**").length <= num)
            return true;
        return false;
    },
    /**
     * 验证字符串最小长度【注：一个汉字的长度为2】
     * @param source 字符串
     * @param num 指定的长度
     */
    textMinVer: function (source, num) {
        if (source.replace(/[^\x00-\xff]/g, "**").length >= num)
            return true;
        return false;
    },
    /** 身份证验证 */
    identityVer: function (identity) {
        if (identity != null && identity != "" && verificatRet.identityCard.test(identity)) {
            return true;
        }
        return false;
    },
    /** 手机号验证 */
    mobileVer: function (mobile) {
        if (mobile != null && mobile != "" && verificatRet.mobile.test(mobile)) {
            return true;
        }
        return false;
    },
    /** 邮箱验证 */
    emailVer: function (email) {
        if (email != null && email != "" && verificatRet.email.test(email)) {
            return true;
        }
        return false;
    },
    /** 电话验证 */
    phoneVer: function (phone) {
        if (phone != null && phone != "" && verificatRet.phone.test(mobile)) {
            return true;
        }
        return false;
    },
    /** 验证是否为正整数 */
    numberVer: function (num) {
        if (num != "") {
            return verificatRet.number.test(num);
        } else {
            return false;
        }
    },
    /** 验证非零正整数 */
    NZ_numberVer: function (num) {
        if (num != "") {
            return verificatRet.NZ_number.test(num);
        } else {
            return false;
        }
    },
    /** 验证非零负整数 */
    _NZ_numberVer: function (num) {
        if (num != "") {
            return verificatRet._NZ_number.test(num);
        } else {
            return false;
        }
    },
    /** 验证非负整数（正整数 + 0） */
    _noIntNumberVer: function (num) {
        if (num != "") {
            return verificatRet._noIntNumber.test(num);
        } else {
            return false;
        }
    },
    /** 验证非正整数（负整数 + 0） */
    noIntNumberVer: function (num) {
        if (num != "") {
            return verificatRet.noIntNumber.test(num);
        } else {
            return false;
        }
    },
    /** 验证整数 */
    intNumberVer: function (num) {
        if (num != "") {
            return verificatRet.intNumber.test(num);
        } else {
            return false;
        }
    },
    /** 验证正浮点小数 */
    doubleNumberVer: function (num) {
        if (num != "") {
            return verificatRet.doubleNumber.test(num);
        } else {
            return false;
        }
    },
    /** 验证非正浮点小数（负浮点小数 + 0） */
    _noDoubleNumVer: function (num) {
        if (num != "") {
            return verificatRet._noDoubleNum.test(num);
        } else {
            return false;
        }
    },
    /** 验证负浮点小数 */
    _doubleNumberVer: function (num) {
        if (num != "") {
            return verificatRet._doubleNumber.test(num);
        } else {
            return false;
        }
    },
    /** 验证浮点小数 */
    doubleVer: function (num) {
        if (num != "") {
            return verificatRet.double.test(num);
        } else {
            return false;
        }
    }
}
utils.keyDwonEvent = function (obj) {
    $(document).keydown(function (event) {
        if (event.keyCode == 13) {
            obj();
        }
    });
}
utils.loginOut = function () {
    $.cookie("token", null, {path: "/"});
    location.href = "/login.html"
}

utils.setUserName = function ($id) {
    $id.text($.cookie("userName"));
}

utils.msgUtil = msgUtil;
utils.initSelectUtil = initSelectUtil;
utils.autoSetVal = autoSetVal;
utils.autoGetValToObj = autoGetValToObj;
utils.verificatRet = verificatRet;
utils.verificat = verificat;